package com.atguigu.day3.cas;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;


public class CASDemo01 {
    public static void main(String[] args) throws InterruptedException {
//        testAtomicInteger();

//        multiThreadInt();

        multiThreadAtomicInteger();
    }




    private static void multiThreadAtomicInteger() throws InterruptedException {
        Source source = new Source();
        CountDownLatch countDownLatch = new CountDownLatch(100);
        for (int i = 0; i < 100; i++) {
            new Thread(()->{
                for (int i1 = 0; i1 < 100; i1++) {
                    source.setAtomicInteger();
                    source.getAtomicInteger().get();
                }
                countDownLatch.countDown();

            }).start();
        }
        countDownLatch.await();
        System.out.println(Thread.currentThread().getName() + source.getAtomicInteger().get());
    }

    private static void multiThreadInt() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(100);
        Source source = new Source();

        for (int i = 0; i < 100; i++) {
            new Thread(()->{
                for (int i1 = 0; i1 < 100; i1++) {
                    source.setNumber();
                    source.getNumber();
                }
                countDownLatch.countDown();
            }).start();
        }

//        Thread.sleep(1000);
        countDownLatch.await();
        System.out.println(Thread.currentThread().getName() + source.getNumber());
    }

    private static void testAtomicInteger() {
        AtomicInteger atomicInteger = new AtomicInteger(0);

        System.out.println(atomicInteger.getAndIncrement());
        System.out.println(atomicInteger);

        atomicInteger.compareAndSet(1, 2024);
        System.out.println("atomicInteger = " + atomicInteger);
        atomicInteger.compareAndSet(1, 2025);
        System.out.println(atomicInteger.get());
    }
}



class Source{
    private int number;
    private AtomicInteger atomicInteger = new AtomicInteger();

    public synchronized void setNumber(){  //不加锁时,同时进行读写,数据出现异常
        ++number;
    }
    public void setAtomicInteger(){
        atomicInteger.incrementAndGet();
//        System.out.println(atomicInteger.get());
    }

    public int getNumber() {
//        System.out.println(number);
        return number;
    }

    public AtomicInteger getAtomicInteger() {
//        System.out.println(atomicInteger.get());
        return atomicInteger;
    }
}